#!/usr/bin/env python
# -*- coding: utf-8 -*-
#####################################################################
#  install: gitpython git-review requests eventlet before start it. #
#  author: weizj                                                    #
#  date: 2018-1-10                                                  #
#  version: 6.0                                                     #
#####################################################################

import os
import eventlet
import greenlet
import traceback

from eventlet.queue import Queue
from constants import *
from committer import Committer
from collector import Collector


if not os.path.exists(PATCH_FILE):
    os.system("touch %s " % PATCH_FILE)


def spawn(*args, **kwargs):
    def _launch(func, *args, **kwargs):
        try:
            func(*args, **kwargs)
        except greenlet.GreenletExit:
            pass
        except:
            LOG.error("[main] uncaught exception: %s." % traceback.format_exc())

    return eventlet.spawn(_launch, *args, **kwargs)


def collector(queue, notify):
    try:
        obj = Collector(queue, notify)
        obj.process_scan()
    except:
        LOG.error("[main] collector failed: %s." % traceback.format_exc())


def committer(queue, notify):
    try:
        obj = Committer(queue, notify)
        obj.process_event()
    except:
        LOG.error("[main] committer failed: %s." % traceback.format_exc())


def main():
    polling_q = Queue(1024)
    notify_q = Queue(512)
    thread1 = spawn(committer, polling_q, notify_q)
    thread2 = spawn(collector, polling_q, notify_q)
    thread2.wait()
    thread1.wait()


if __name__ == "__main__":
    try:
        main()
    except:
        LOG.error("[main] %s" % traceback.format_exc())

